<?php

/**
 * 用户提醒模型
 */

namespace app\api\model;


use app\common\lib\RespCode;
use custom\Token;
use PDOStatement;
use think\Collection;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class UserRemind {

    //1：房源，2：小区
    const R_TYPE1 = 1;
    const R_TYPE2 = 2;

    /**
     * 用户提醒
     * @param $params
     * @return int|string
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function add($params) {
        //房源
        if ($params['r_type'] == self::R_TYPE1)
            $data = Db::name("house")
                ->where('is_shelf', 1)
                ->find($params['id']);

        //小区
        if ($params['r_type'] == self::R_TYPE2)
            $data = Db::name("house_village")
                ->find($params['id']);

        if (empty($data)) throw new Exception('房源已下架', RespCode::DATA_ERR);

        $user_remind = Db::name("user_remind")
            ->where('remind_id', $params['id'])
            ->where('user_id', $params['user_id'])
            ->where("remind_type", $params['r_type'])
            ->find();
        if (!empty($user_remind)) throw new Exception('请勿重复添加', RespCode::DATA_ERR);

        if ($params['r_type'] == self::R_TYPE1) {
            if (db('user_remind')
                    ->where('user_id', $params['user_id'])
                    ->where('remind_type', 1)
                    ->count()
                >= 10)
                throw new Exception('最多添加10个提醒房源', RespCode::DATA_ERR);
        }

        if ($params['r_type'] == self::R_TYPE2) {
            if (db('user_remind')
                    ->where('user_id', $params['user_id'])
                    ->where('remind_type', 2)
                    ->count()
                >= 3)

                throw new Exception('最多添加3个提醒小区', RespCode::DATA_ERR);
        }

        $insert = [
            'user_id' => $params['user_id'],
            'remind_id' => $params['id'],
            'remind_type' => $params['r_type'],
            'itime' => time(),
        ];
        $res = Db::name('user_remind')->insert($insert);
        if (!$res) {
            throw new Exception('操作失败');
        }
        return true;
    }

    /**
     * 删除提醒
     * @param $params
     * @return int
     * @throws Exception
     * @throws PDOException
     */
    public static function del($params) {
        $ids = $params['ids'];
        $ids = explode(',', $ids);
        //房源
        if ($params['r_type'] == 1) {
            foreach ($ids as $k => $v) {
                Db::name('user_remind')
                    ->where('user_id', $params['user_id'])
                    ->where('remind_type', 1)
                    ->where('remind_id', $v)
                    ->delete();
            }
        }
        //小区
        if ($params['r_type'] == 2) {
            foreach ($ids as $k => $v) {
                Db::name('user_remind')
                    ->where('user_id', $params['user_id'])
                    ->where('remind_type', 2)
                    ->where('remind_id', $v)
                    ->delete();
            }
        }
    }

    /**
     * 提醒房源/小区
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function show($params) {
        if ($params['r_type'] == 1) {
            //房源
            $map = [];
            $house = new House();
            $column = array_merge($house->houseFields, $house->villageFields, $house->typeFields, $house->auctionFields,$house->businessFields,$house->reginFields);
            if (!empty($params['title'])) {
                $map[] = ['h.title', 'like', '%' . trim($params['title']) . '%'];
            }
            $remind_id = Db::name('user_remind')
                ->where('user_id', $params['user_id'])
                ->where('remind_type', 1)
                ->order('id', 'desc')
                ->column('remind_id');
            $map[] = ['h.id', 'in', $remind_id];
            $remind_id_str = join(',', $remind_id);
            $res = $house->house_list($map, '', $column, 1, 10, [], $remind_id_str)[0];
            return House::house_list_style($res);
        } else {
            //小区
            $map = [];
            $column = ['hv.name', 'hv.total_num', 'hv.id', 'hv.city_code', 'hv.years', 'hv.price_unit_avg as average_price', 'hv.cover', 'r1.p_code', 'r1.name as area_name', 'r2.name as city_name'];
            if (!empty($params['title'])) {
                $map[] = ['hv.name', 'like', '%' . trim($params['title']) . '%'];
            }
            $village_id = db('user_remind')
                ->where('remind_type', 2)
                ->where('user_id', $params['user_id'])
                ->order('id', 'desc')
                ->column('remind_id');
            $orderby = [];
            $map[] = ['hv.id', 'in', $village_id];
            $orderRaw = join(',', $village_id);
            HouseVillage::sql_list($map, $column, 1, 10, $orderby, $orderRaw, $page, $pageNum, $data, $count);
            return $data;
        }
    }

    /**
     * 用户是否添加房源提醒
     * @param $params
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function isRemind($params, $type) {
        return Db::name('user_remind')
            ->where('remind_type', $type)
            ->where('user_id', $params['user_id'])
            ->where('remind_id', $params['id'])
            ->find();
    }


}
